#include "sys_control.h"
#include "ui_mainwindow.h"

sys_Control::sys_Control(Ui::MainWindow *_ui, QObject *parent)
    : QObject(parent)
    , ui(_ui)
    , m_dlgDiskfile(new dlg_DiskFile)
    , m_imgFile(new img_File)
    , m_imgViewer(new img_Viewer(ui->vtkWidget_viewA->GetRenderWindow(),
                                 ui->vtkWidget_viewC->GetRenderWindow(),
                                 ui->vtkWidget_viewS->GetRenderWindow(),
                                 ui->vtkWidget_view3DSlice->GetRenderWindow(),
                                 ui->vtkWidget_view3DInfection->GetRenderWindow(),
                                 this))
    , m_anlsCore(new anls_Core(ui->statusBar,
                               ui->progressBar_analysis,
                               this))
{
    connect(m_anlsCore, anls_Core::getDataFinish, this, this->analysisDataFinish);
    //-------------------------------------------------------------------------------------------
    connect(m_imgViewer->getAxilaWidget(), img_Widget::sliceChange, this,
    [&](int _slice) {
        ui->vScrollBar_viewA->setValue(_slice);
        ui->label_viewA->setText(
            QString("%1 of %2").arg(_slice).arg(m_imgFile->info().dim[img_Widget::AXIAL + 1]));
        syneUI();
    });
    connect(m_imgViewer->getCoronalWidget(), img_Widget::sliceChange, this,
    [&](int _slice) {
        ui->vScrollBar_viewC->setValue(_slice);
        ui->label_viewC->setText(
            QString("%1 of %2").arg(_slice).arg(m_imgFile->info().dim[img_Widget::CORONAL + 1]));
        syneUI();
    });
    connect(m_imgViewer->getSagittalWidget(), img_Widget::sliceChange, this,
    [&](int _slice) {
        ui->vScrollBar_viewS->setValue(_slice);
        ui->label_viewS->setText(
            QString("%1 of %2").arg(_slice).arg(m_imgFile->info().dim[img_Widget::SAGITTAL + 1]));
        syneUI();
    });
    //-------------------------------------------------------------------------------------------
    connect(m_imgViewer->getCallBack(), vtkCallback::windowLevelChange, this,
    [&](double _window, double _level) {
        ui->lineEdit_window->setText(QString::number(_window));
        ui->lineEdit_level->setText(QString::number(_level));
    });
}

sys_Control::~sys_Control()
{
    delete this->m_dlgDiskfile;
    delete this->m_imgFile;
}

void sys_Control::openDiskFile()
{
    this->m_dlgDiskfile->openFile(this->m_imgFile);
    if(this->m_imgFile->isOpen()) {
        this->initImgWidget();
        sys_Data::getInstance()->addOpenFileHistory(this->m_imgFile->getFileName());
    }
}

void sys_Control::setImgFile(const QString &fileName)
{
    this->m_imgFile->openFile(fileName);
    this->initImgWidget();
    sys_Data::getInstance()->addOpenFileHistory(fileName);
}

void sys_Control::show3DInfection()
{
    m_imgViewer->set3DInfection(m_anlsData->data);
}

void sys_Control::showMessage()
{
    m_dlgMessage.initQSS();
    m_dlgMessage.exec();
}

void sys_Control::setSetting()
{
    m_dlgSetting.setSetting();
}

void sys_Control::openAnalysisFile()
{
    img_File anlsFile;
    m_dlgDiskfile->openFile(&anlsFile);
    if(anlsFile.isOpen()) {
        m_anlsData = new anls_Data;
        m_anlsData->data = anlsFile.reader()->GetOutput();
        if(anlsFile.info().descrip.length() == 73) {//读取到推理信息
            DESCRIPT temp;
            const char *str = anlsFile.reader()->GetNIFTIHeader()->GetDescrip();
            for(int i = 0; i < 73; i++) {
                temp.str[i] = str[i];
            }
            for(int i = 0; i < 6; i++) {
                m_anlsData->volume[i] = temp.value[i];
                m_anlsData->lesionVolume[i] = temp.value[i + 6];
                m_anlsData->lesionDensity[i] = temp.value[i + 12];
            }
        }
        m_dlgMessage.setMessage(*m_anlsData);
        ui->statusBar->showMessage(QString("已载入\"%1\"").arg(anlsFile.info().fileName));
        initAnlsWidget();
    }
}

void sys_Control::analysisImg()
{
    if(m_imgFile->isOpen()) {
        m_anlsCore->analysisImg(&m_imgFile->info());
    }
}

void sys_Control::analysisDataFinish(anls_Data &_data)
{
    m_anlsData = &_data;
    m_dlgMessage.setMessage(_data);
    ui->statusBar->showMessage("智能分析已经完成！");
    ui->progressBar_analysis->setValue(100);
    initAnlsWidget();
}

void sys_Control::showAnlsImg()
{
    m_imgViewer->setAnalysisImg(m_anlsData->data);
}

void sys_Control::saveAnalysis()
{
    QFileDialog fileDialog;
    //不使用标准文件对话框
    fileDialog.setOption(QFileDialog::DontUseNativeDialog);
    //去掉文件对话框边框
    fileDialog.setWindowFlag(Qt::FramelessWindowHint);
    fileDialog.setAcceptMode(QFileDialog::AcceptSave);
    fileDialog.setDefaultSuffix("nii");
    fileDialog.setNameFilter("*.nii");
    fileDialog.setStyleSheet(sys_Data::getInstance()->getThemeQss());
    foreach(QPushButton* btn, fileDialog.findChildren<QPushButton*>()) {
        btn->setFixedSize(80, 20);//设置文件对话框按钮大小
    }
    if(fileDialog.exec() == QFileDialog::AcceptSave) {
        QStringList path = fileDialog.selectedFiles();
        vtkSmartPointer<vtkNIFTIImageWriter> writer = vtkSmartPointer<vtkNIFTIImageWriter>::New();
        DESCRIPT temp;
        writer->SetFileName(path.first().toStdString().c_str());
        writer->SetInputData(m_anlsData->data);
        for(int i = 0; i < 6; i++) {
            temp.value[i] = m_anlsData->volume[i];
            temp.value[i + 6] = m_anlsData->lesionVolume[i];
            temp.value[i + 12] = m_anlsData->lesionDensity[i];
        }
        temp.str[3 * 6 * 4] = '/0';//字符串结尾标志
        writer->SetDescription(temp.str);
        writer->Write();
        ui->statusBar->showMessage(QString("\"%1\"保存成功").arg(path.first()), 3000);
    }
}

void sys_Control::saveWindowShot(vtkRenderWindow *_window)
{
    QFileDialog fileDialog;
    //不使用标准文件对话框
    fileDialog.setOption(QFileDialog::DontUseNativeDialog);
    //去掉文件对话框边框
    fileDialog.setWindowFlag(Qt::FramelessWindowHint);
    fileDialog.setAcceptMode(QFileDialog::AcceptSave);
    fileDialog.setDefaultSuffix("png");
    fileDialog.setNameFilter("*.png");
    fileDialog.setStyleSheet(sys_Data::getInstance()->getThemeQss());
    foreach(QPushButton* btn, fileDialog.findChildren<QPushButton*>()) {
        btn->setFixedSize(80, 20);//设置文件对话框按钮大小
    }
    if(fileDialog.exec() == QFileDialog::AcceptSave) {
        QStringList path = fileDialog.selectedFiles();
        vtkSmartPointer<vtkWindowToImageFilter> img = vtkSmartPointer<vtkWindowToImageFilter>::New();
        img->SetInput(_window);
        img->SetScale(1);
        img->SetInputBufferTypeToRGB();
        img->ReadFrontBufferOff();
        img->Update();
        vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter>::New();
        writer->SetFileName(path.first().toStdString().c_str());
        writer->SetInputData(img->GetOutput());
        writer->Write();
        ui->statusBar->showMessage(QString("\"%1\"保存成功").arg(path.first()), 3000);
    }
}

void sys_Control::setDangerUIClose()
{
    ui->frame_control->setEnabled(false);
    ui->frame_analysis->setEnabled(false);
    ui->frame_anlsImg->setEnabled(false);
    ui->frame_viewSetting->setEnabled(false);
    ui->btn_saveAnalysis->setEnabled(false);
    ui->btn_view3D_reset->setEnabled(false);
    ui->btn_view3D_axes->setEnabled(false);
    ui->action_segmentation_open->setEnabled(false);
    ui->action_segmentation_analysis->setEnabled(false);
    ui->action_segmentation_save->setEnabled(false);
}

img_Viewer *sys_Control::getImgViewer() const
{
    return m_imgViewer;
}

void sys_Control::setUI()
{
    ui->vScrollBar_viewA->setMaximum(m_imgFile->info().dim[img_Widget::AXIAL + 1]);
    ui->vScrollBar_viewC->setMaximum(m_imgFile->info().dim[img_Widget::CORONAL + 1]);
    ui->vScrollBar_viewS->setMaximum(m_imgFile->info().dim[img_Widget::SAGITTAL + 1]);
    ui->lineEdit_window->setText(QString::number(m_imgFile->getWindow()));
    ui->lineEdit_level->setText(QString::number(m_imgFile->getLevel()));
    emit fileOpened(m_imgFile->getFileName());
}

void sys_Control::syneUI()
{
    setPosition();
    setCurrentPix();
    ui->vtkWidget_view3DSlice->GetRenderWindow()->Render();
}

void sys_Control::setPosition()
{
    int position[3] = {0};
    m_imgViewer->getCurrentPosition(position);
    ui->lineEdit_cursorPositionX->setText(QString::number(position[0]));
    ui->lineEdit_cursorPositionY->setText(QString::number(position[1]));
    ui->lineEdit_cursorPositionZ->setText(QString::number(position[2]));
}

void sys_Control::setCurrentPix()
{
    ui->lineEdit_cursorValue->setText(QString::number(m_imgViewer->getCurrentPix()));
}

void sys_Control::initImgWidget()
{
    this->setUI();
    this->m_imgViewer->setImg(this->m_imgFile);
    //----------------------------------------------------------------------------
    ui->frame_control->setEnabled(true);
    ui->frame_analysis->setEnabled(true);
    ui->frame_viewSetting->setEnabled(true);
    ui->btn_view3D_reset->setEnabled(true);
    ui->btn_view3D_axes->setEnabled(true);
    ui->action_segmentation_open->setEnabled(true);
    ui->action_segmentation_analysis->setEnabled(true);
    //----------------------------------------------------------------------------
    ui->btn_saveAnalysis->setEnabled(false);
    ui->frame_anlsImg->setEnabled(false);
    ui->checkBox_anlsImg->setChecked(false);
    ui->action_segmentation_save->setEnabled(false);
    m_imgViewer->unSet3DInfection();
    //----------------------------------------------------------------------------
    tabFlag = true;
    ui->widget_view3D->setCurrentIndex(0);
    ui->btn_tab->setText("查看3D病灶");
    modeFlag = true;
    m_imgViewer->setCrossLineMode(false);
    ui->btn_mode->setText("十字线模式");
    ui->progressBar_analysis->setValue(0);
}

void sys_Control::initAnlsWidget()
{
    ui->btn_saveAnalysis->setEnabled(true);
    ui->frame_anlsImg->setEnabled(true);
    ui->action_segmentation_save->setEnabled(true);
}
